<template>
  <div id="spaceUserManagePage">
    <a-flex justify="space-between">
      <h2 style="margin-left: 100px">空间成员管理</h2>
      <a-space style="margin-right: 100px">
        <a-button type="primary" href="/add_space" :icon="h(CloudOutlined)"> 创建空间</a-button>
        <a-button
          type="primary"
          ghost
          href="/space_analyze?queryPublic=1"
          target="_blank"
          :icon="h(BarChartOutlined)"
        >
          公共图库分析
        </a-button>
        <a-button
          type="primary"
          ghost
          href="/space_analyze?queryAll=1"
          target="_blank"
          :icon="h(BarChartOutlined)"
        >
          全部空间分析
        </a-button>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 12px" />
    <!-- 添加成员表单 -->
    <a-form layout="inline" :model="formData" @finish="handleSubmit">
      <a-form-item label="用户ID" name="userId">
        <a-input v-model:value="formData.userId" placeholder="请输入用户 id" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">添加用户</a-button>
      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 空间数据表单 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :scroll="{ x: 1300, y: 469 }"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userInfo'">
          <a-space>
            <a-avatar :src="record.user?.userAvatar" />
            {{ record.user?.userName }}
          </a-space>
        </template>
        <template v-if="column.dataIndex === 'spaceRole'">
          <a-select
            v-model:value="record.spaceRole"
            :options="SPACE_ROLE_OPTIONS"
            @change="(value) => editSpaceRole(value, record)"
          />
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <!-- 移除某位成员 气泡确认框 -->
            <a-popconfirm
              title="确定移除这位成员吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
              @cancel="cancelDelete"
            >
              <a href="#">
                <a-button :icon="h(DeleteOutlined)" type="link" danger title="移除该名成员">移除 Ta</a-button>
              </a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, h } from 'vue'
import {
  deleteSpaceUsingPost,
  listSpaceByPageUsingPost,
  listSpaceLevelUsingGet,
} from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import {
  EditOutlined,
  DeleteOutlined,
  CloudOutlined,
  BarChartOutlined,
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { SPACE_ROLE_OPTIONS } from '../../constants/space.ts'
import {
  addSpaceUserUsingPost,
  deleteSpaceUserUsingPost,
  editSpaceUserUsingPost,
  listSpaceUserUsingPost,
} from '@/api/spaceUserController.ts'

// 空间管理表格第一行信息
const columns = [
  {
    title: '成员信息',
    dataIndex: 'userInfo',
  },
  {
    title: 'Ta 的权限（可选择修改）',
    dataIndex: 'spaceRole',
  },
  {
    title: '加入时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据类型
const dataList = ref<API.SpaceUserVO[]>([])

const loading = ref(true)

interface Props {
  id: string
}

const props = defineProps<Props>()

// 根据搜索条件，远程获取数据
const fetchData = async () => {
  loading.value = true
  const spaceId = props.id
  if (!spaceId) {
    message.error('参数非法')
    return
  }
  const res = await listSpaceUserUsingPost({
    // @ts-ignore
    spaceId,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取空间成员数据失败，' + res.data.message)
  }
  loading.value = false
}

// 首次进入空间管理页面，请求一次默认搜索的空间数据
onMounted(() => {
  fetchData()
})

// 添加新成员表单
const formData = reactive<API.SpaceUserAddRequest>({})

/**
 * 添加新成员
 */
const handleSubmit = async () => {
  const spaceId = props?.id
  if (!spaceId) {
    return
  }
  const res = await addSpaceUserUsingPost({
    // @ts-ignore
    spaceId,
    ...formData,
  })
  if (res.data.code === 0) {
    message.success('添加成员成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('添加成员失败，' + res.data.message)
  }
}

/**
 * 编辑成员权限
 * @param value
 * @param record
 */
// @ts-ignore
const editSpaceRole = async (value, record) => {
  const res = await editSpaceUserUsingPost({
    id: record.id,
    spaceRole: value,
  })
  if (res.data.code === 0) {
    message.success('修改权限成功')
  } else {
    message.error('修改权限失败，' + res.data.message)
  }
}

/**
 * 移除某位成员
 * @param id
 */
const doDelete = async (id: String) => {
  // 前端校验一下id是否有效
  if (!id) {
    return
  }
  // @ts-ignore
  const res = await deleteSpaceUserUsingPost({ id })
  if (res.data.code === 0) {
    message.success('移除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('移除失败，' + res.data.message)
  }
}

/**
 * 取消删除空间
 * @param e
 */
const cancelDelete = (e: MouseEvent) => {
  message.success('取消移除成员')
}

/**
 * 用于搜索框默认展示空间级别字段
 */
const getSpaceLevelOptions = async () => {
  const res = await listSpaceLevelUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('默认分类标签列表展示失败，' + res.data.message)
  }
}

onMounted(() => {
  getSpaceLevelOptions()
})
</script>

<style scoped>
.spaceName {
  margin-left: 300px;
}
</style>
